// * 
// * ExPOUND add Layer 
// * 
// * 
// * @copyright 2007 Loughborough University
// * @license http://www.gnu.org/licenses/gpl.txt
// * @version 0.0.0.1
// * @since November 2009
// * /


import classes.Layer;
import classes.Page;

import flash.errors.IOError;
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.FileFilter;
import flash.net.FileReference;
import flash.net.URLRequest;

import mx.controls.Alert;
import mx.core.Application;
import mx.managers.PopUpManager;

import mxml_views.AudioClipping;
import mxml_views.add_layer;

include "pagedrawing.as";

public var win:add_layer;

private var AudioFileReference:FileReference = new FileReference();
private var ImageFileReferenece:FileReference = new FileReference();

private var AudioAssetLocation:String = Application.application.serverURL + "save/audio_asset.php";
private var ImageAssetLocation:String = Application.application.serverURL + "save/image_asset.php";
//private var AssetFolder:String = "users/" + Application.application.currentUser + "/" +  Application.application._ProjectProperties._projectName + "/assets/";
private var AssetFolder:String;

           
private function displayAddLayer():void {
	win = add_layer(PopUpManager.createPopUp(this, add_layer, true));
	PopUpManager.centerPopUp(win);
	
	//add an event listener for the save functionality
	win["btnOkay"].addEventListener("click", handleSave);
	
}

//when the okay button on the add layer form is clicked
//we want to trigger this area of code to pick up the details entred
//and load them to the list and array collection for the list
private function handleSave(event:Event):void{
	
	//check to see that we are associated with a page, before allowing the user to add
	if (Application.application.currentPageSelected==null){
		
		Alert.show("There are no pages created / selected, so no layers can be created");
	}else{
	
		//save the details to the correct layer class instance
		var tempPageclass:Page = new Page;
		tempPageclass = Application.application._ProjectProperties._pages[Application.application.currentPageSelected];
		
		tempPageclass.height = Application.application.default_height;
		tempPageclass.width = Application.application.default_width;
		
		//save the details of the layer to a new instance of the layers within the page class
		var tempLayer:Layer =  new Layer;
		tempLayer.label = String(win.txtName.text);
		tempLayer.data = String(win.LayerType.selectedValue);
		tempLayer.icon = "Bullet" + String(win.LayerType.selectedValue);
		tempLayer.visability = true;
		tempLayer.stacking_order = 0;
		tempLayer.sequencing_on_time = 0;
		tempLayer.sequencing_off_time = 0;
		tempLayer.opacity = String(100);
		
		tempPageclass.layers.push(tempLayer);
		
		//set the current layer
		Application.application.currentLayerSelected = tempPageclass.layers.length -1;
		
		var CurrentLayersXML:XML = tempPageclass.PublicDisplayLayers();
		
		Application.application.layers.Layers.dataProvider =  CurrentLayersXML.layer;
		
	 
		 //@todo need to call layer auto save
		 
		var StrSwitch:String = String(win.LayerType.selectedValue);	 
		//trigger the forms that need to be opened
		switch(StrSwitch){
	    	case "Audio": 	
	    		//if an image layer - launch the image browse
	    		BrowseAudio();
	        	break;
	        case "Image":							//if the audio is selected launch the audio browse
	        	BrowseImage();
	        	break;
	        case "Text":
	        	//set-up the text elements of the layer to prevent the tool erroring
	        	tempLayer.obj_display_text = "";
	        	tempLayer.obj_original_text = "";
	        	PopUpManager.createPopUp(Application.application.Expound_Container,text_editor, true);
	        	PopUpManager.removePopUp(win);
	        case "Drawing":    	
	        	ClearPage();
	        	DrawSelectedPage(Application.application.currentPageSelected);	        	
	        	PopUpManager.removePopUp(win);
			default:								//add the layer to the main canvas area of the screen
	        	
	        	break;
		}
	}

}

public function BrowseAudio():void{

	AssetFolder = "users/" + Application.application.currentUser + "/" + Application.application._ProjectProperties._projectName.toString() + "/assets/";
	
	var AudioFilter:FileFilter = new FileFilter("Audio (*.mp3)", "*.mp3");
	var ArrFileTypes:Array = new Array(AudioFilter);
	
	AudioFileReference.addEventListener(Event.SELECT, UploadAudio);
	AudioFileReference.addEventListener(Event.COMPLETE, OpenAudioLayer);
	AudioFileReference.addEventListener(SecurityErrorEvent.SECURITY_ERROR,SecurityError);
	AudioFileReference.addEventListener(HTTPStatusEvent.HTTP_STATUS,StatusEvent);
	AudioFileReference.addEventListener(IOErrorEvent.IO_ERROR,IOErrorHandler);
	AudioFileReference.browse(ArrFileTypes);
	
	PopUpManager.removePopUp(win);
}

public function UploadAudio(event:Event):void{
	
	var toUpload:URLRequest = new URLRequest()
	
	var urlVars:URLVariables = new URLVariables();
	urlVars.targetFolder     = AssetFolder
	toUpload.method          = URLRequestMethod.POST;
	toUpload.data            = urlVars;

	var fileRef:FileReference = FileReference(event.target);

    toUpload.url = AudioAssetLocation;
    toUpload.method = URLRequestMethod.POST;
  
    AudioFileReference = fileRef;
    AudioFileReference.addEventListener(Event.COMPLETE, OpenAudioLayer);
    AudioFileReference.addEventListener(IOErrorEvent.IO_ERROR, IOErrorHandler);
    AudioFileReference.addEventListener(SecurityErrorEvent.SECURITY_ERROR, SecurityError);
    AudioFileReference.upload(toUpload, "file", false);

}

public function OpenAudioLayer(event:Event):void{
	//this function is called after the file has uploaded
	//a new layer is opened over the e-proofbuild area displaying the audio clipping tool
	
	//prior to opening the audio layer information we need to save this information to the
	//new audio uploaded
	var thisPage:Page = new Page();
	thisPage = Application.application._ProjectProperties._pages[Application.application.currentPageSelected];
	var thisLayer:Layer = new Layer();
	thisLayer = thisPage.layers[length -1];
	thisLayer.obj_file_location = AudioFileReference.name;

	PopUpManager.createPopUp(Application.application.Expound_Container,AudioClipping, true);
}

public function SecurityError(event:SecurityErrorEvent):void{
	Alert.show("securityErrorHandler: " + event);

}

public function StatusEvent(event:HTTPStatusEvent):void{
	Alert.show("HTTPStatus ErrorHandler: " + event);
	Alert.show(event.bubbles.toString());

}

public function IOErrorHandler(event:IOError):void{
	Alert.show("IO Error ErrorHandler: " + event.getStackTrace());


}

public function BrowseImage():void{
	
	var strProjectFolder:String = new String;
	strProjectFolder = StripStringSpaces(Application.application._ProjectProperties._projectName.toString());

	AssetFolder = "users/" + Application.application.currentUser + "/" + strProjectFolder + "/assets/";
	
	var ImageFilter:FileFilter = new FileFilter("Images (*.png, *.jpg, *.jpeg, *.gif)", "*.png, *.jpg; *.jpeg; *.gif");
	var ArrFileTypes:Array = new Array(ImageFilter);

	ImageFileReferenece.addEventListener(Event.SELECT, UploadImage);
	ImageFileReferenece.addEventListener(SecurityErrorEvent.SECURITY_ERROR,SecurityError);
	ImageFileReferenece.addEventListener(HTTPStatusEvent.HTTP_STATUS,StatusEvent);
	ImageFileReferenece.addEventListener(IOErrorEvent.IO_ERROR,IOErrorHandler);
	ImageFileReferenece.browse(ArrFileTypes);
	
	PopUpManager.removePopUp(win);
}

public function UploadImage(event:Event):void{
//Alert.show("We are going to upload the image!");

	var fileRef:FileReference = FileReference(event.target);
//Alert.show(fileRef.name);		
//Alert.show(ImageAssetLocation);
	var toUpload:URLRequest = new URLRequest()
	
	var urlVars:URLVariables = new URLVariables();
	urlVars.targetFolder     = AssetFolder
	toUpload.method          = URLRequestMethod.POST;
	toUpload.data            = urlVars;

    toUpload.url = ImageAssetLocation;
    toUpload.method = URLRequestMethod.POST;
  
    ImageFileReferenece = fileRef;
    ImageFileReferenece.addEventListener(Event.COMPLETE, OpenImageLayer);
    ImageFileReferenece.addEventListener(IOErrorEvent.IO_ERROR, IOErrorHandler);
    ImageFileReferenece.addEventListener(SecurityErrorEvent.SECURITY_ERROR, SecurityError);
    ImageFileReferenece.upload(toUpload, "file", false);
}

public function OpenImageLayer(event:Event):void{
	var thisPage:Page = new Page();
	thisPage = Application.application._ProjectProperties._pages[Application.application.currentPageSelected];
	var thisLayer:Layer = new Layer();
	thisLayer = thisPage.layers[length -1];
	thisLayer.obj_file_location = ImageFileReferenece.name;
	thisLayer.obj_currentheight = 100;
	thisLayer.obj_currentwidth = 100;
	
	
	ClearPage();
	DrawSelectedPage(Application.application.currentPageSelected);
	
}